package TencentCloud

import (
	"duoke/model"
	utils "duoke/utils/common"
	"duoke/utils/gstr"
	"duoke/utils/yaml"
	"encoding/json"
	"fmt"
	"github.com/tencentyun/tls-sig-api-v2-golang/tencentyun"
)

var TencentImUtils = new(imUtils)

type imUtils struct{}

func SetParam(req *model.ParamsIm) (string, error) {
	config := yaml.GetConfig()
	im := config.TencentIm
	random := gstr.Random(32)
	identifier := "administrator"
	signature, err := tencentyun.GenUserSig(im.SdkAppid, im.SecretKey, identifier, 86400*180)
	if err != nil {
		return "", err
	}
	url := fmt.Sprintf("%s/%s?sdkappid=%d&identifier=%s&usersig=%s&random=%s&contenttype=json",
		im.Domain, req.Url, im.SdkAppid, identifier, signature, random)
	return url, nil
}

// 封装公共的POST请求逻辑
func (u *imUtils) sendPostRequest(url string, reqBody interface{}) ([]byte, error) {
	marshal, err := json.Marshal(reqBody)
	if err != nil {
		return nil, fmt.Errorf("请求体序列化失败: %v", err)
	}

	response, err := utils.Common.PostCurl(marshal, url)
	if err != nil {
		return nil, fmt.Errorf("HTTP请求失败: %v", err)
	}
	return response, nil
}

func (u *imUtils) SendIMRequest(url string, req interface{}) ([]byte, error) {
	return u.sendPostRequest(url, req)
}
